<template>
  <view class="refund-container">
    <!-- 状态筛选 -->
    <view class="status-tabs">
      <view
        v-for="(label, status) in statusTabs"
        :key="status"
        :class="['status-tab', {active: activeStatus === status}]"
        @click="activeStatus = status"
      >
        {{ label }}
      </view>
    </view>
    <!-- 退款统计 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-value">{{stats.pending}}</text>
        <text class="stat-label">待处理</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{stats.approved}}</text>
        <text class="stat-label">已同意</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{stats.rejected}}</text>
        <text class="stat-label">已拒绝</text>
      </view>
    </view>

    <!-- 退款列表 -->
    <view class="refund-list">
      <view class="refund-item" v-for="(refund, index) in filteredRefunds" :key="refund.rrId" @click="goToDetail(refund.rrId)">
        <view class="refund-header">
          <text class="order-time">{{formatTime(refund.requestTime)}}</text>
          <text class="refund-status" :class="getStatusClass(refund.requestStatus)">{{getStatusText(refund.requestStatus)}}</text>
        </view>
        
        <view class="refund-content">
          <view class="order-info">
            <text class="order-id">订单号：{{refund.orderId}}</text>
            <text class="refund-amount">申请金额：¥{{refund.requestAmount}}</text>
          </view>
          
          <view class="refund-reason">
            <text class="reason-label">退款原因：</text>
            <text class="reason-text">{{refund.reason}}</text>
          </view>

          <view class="customer-info">
            <text class="customer-name">{{refund.customerName}}</text>
            <text class="customer-phone">{{formatPhone(refund.customerPhone)}}</text>
          </view>
        </view>
      </view>
      <view v-if="filteredRefunds.length === 0" class="empty-data">
        <text class="empty-text">暂无退款记录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import { refundApi } from '../../utils/api.js'

// 响应式数据
const stats = reactive({
  pending: 0,
  approved: 0,
  rejected: 0
})

const refunds = ref([])

// 测试数据
const mockRefundData = {}

// 方法
const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已同意',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

const getStatusClass = (status) => {
  const classMap = {
    0: 'pending',
    1: 'approved',
    2: 'rejected'
  }
  return classMap[status] || 'pending'
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  // 将 "yyyy-MM-dd HH:mm:ss" 格式转换为 "yyyy/MM/dd HH:mm:ss" 格式以兼容iOS
  const formattedTimeStr = timeStr.replace(/-/g, '/')
  const date = new Date(formattedTimeStr)
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.error('无效的日期格式:', timeStr)
    return timeStr // 返回原始字符串
  }
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const goToDetail = (rrId) => {
  uni.navigateTo({
    url: `./refund-detail?rrId=${rrId}`
  })
}

// 手机号脱敏处理
const formatPhone = (phone) => {
  if (!phone) return ''
  // 只处理11位手机号
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 获取退款统计数据
const getRefundStats = async () => {
  try {
    // 调用接口获取统计数据
    const response = await refundApi.getStats()
    stats.pending = response.data.pending
    stats.approved = response.data.approved
    stats.rejected = response.data.rejected
  } catch (error) {
    console.error('获取退款统计失败:', error)
    // 根据退款列表动态计算统计数据
    calculateStatsFromList()
  }
}

// 根据退款列表计算统计数据
const calculateStatsFromList = () => {
  stats.pending = refunds.value.filter(item => item.requestStatus === 0).length
  stats.approved = refunds.value.filter(item => item.requestStatus === 1).length
  stats.rejected = refunds.value.filter(item => item.requestStatus === 2).length
}

// 获取退款列表
const getRefundList = async () => {
  try {
    // 调用接口获取退款列表
    const response = await refundApi.listRefundDTO()
    refunds.value = response.data.map(item => ({
      rrId: item.rrId,
      orderId: item.orderId,
      requestTime: item.requestTime,
      requestStatus: item.requestStatus,
      requestAmount: item.requestAmount,
      actualAmount: item.actualAmount,
      reason: item.reason,
      refundDesc: item.refundDesc,
      refuseReason: item.refuseReason,
      operateTime: item.operateTime,
      customerName: item.customerFullName,
      customerPhone: formatPhone(item.phone)
    }))
    // 根据列表数据计算统计数据
    calculateStatsFromList()
  } catch (error) {
    console.error('获取退款列表失败:', error)
    // 使用模拟数据
    refunds.value = mockRefundData.list.map(item => ({
      ...item,
      customerPhone: formatPhone(item.customerPhone)
    }))
    // 根据列表数据计算统计数据
    calculateStatsFromList()
  }
}

// 生命周期
let refundListTimer = null

onMounted(() => {
  getRefundList()
  // 启动轮询，每30秒刷新一次
  refundListTimer = setInterval(() => {
    getRefundList()
  }, 5000)
})

onUnmounted(() => {
  if (refundListTimer) {
    clearInterval(refundListTimer)
    refundListTimer = null
  }
})

// 状态筛选相关
const statusTabs = {
  all: '全部',
  0: '待处理',
  1: '已同意',
  2: '已拒绝'
}
const activeStatus = ref('all')
const filteredRefunds = computed(() => {
  if (activeStatus.value === 'all') return refunds.value
  return refunds.value.filter(item => String(item.requestStatus) === String(activeStatus.value))
})
</script>

<style>
.refund-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.stats-section {
  display: flex;
  justify-content: space-around;
  background-color: #ffffff;
  padding: 30rpx 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

.refund-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.refund-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
}

.refund-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.order-time {
  font-size: 28rpx;
  color: #333;
}

.refund-status {
  font-size: 26rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.refund-status.pending {
  color: #faad14;
  background-color: #fff7e6;
}

.refund-status.approved {
  color: #52c41a;
  background-color: #f6ffed;
}

.refund-status.rejected {
  color: #ff4d4f;
  background-color: #fff1f0;
}

.refund-content {
  margin-bottom: 20rpx;
}

.order-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.order-id {
  font-size: 28rpx;
  color: #333;
}

.refund-amount {
  font-size: 28rpx;
  color: #C70209;
  font-weight: bold;
}

.refund-reason {
  background-color: #f9f9f9;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.reason-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.reason-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

.customer-info {
  display: flex;
  flex-direction: column;
}

.customer-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.customer-phone {
  font-size: 24rpx;
  color: #999;
}

.status-tabs {
  display: flex;
  justify-content: space-around;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 16rpx 0;
}
.status-tab {
  font-size: 28rpx;
  color: #666;
  padding: 8rpx 32rpx;
  border-radius: 32rpx;
  background: #f5f5f5;
  margin: 0 8rpx;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.status-tab.active {
  color: #fff;
  background: #C70209;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200rpx;
}
.empty-text {
  color: #bbb;
  font-size: 28rpx;
  margin-top: 40rpx;
}
</style> 